package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.DeptDao;
import cn.yunyichina.provider.base.dao.OrgSettingDao;
import cn.yunyichina.provider.base.dao.PlatformDeptRelationDao;
import cn.yunyichina.provider.base.entity.Dept;
import cn.yunyichina.provider.base.entity.PlatformDeptRelation;
import cn.yunyichina.provider.base.utils.StringUtils;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.iface.entity.base.DeptVo;
import cn.yunyichina.provider.iface.entity.base.OrgSetting;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterDeptsVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterDeptsVoResponse;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.PinyinUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * @projectName:yyt-provider-base
 * @author:yangfan
 * @description:医院科室service
 * @date:2016年11月8日
 * @className:DeptServiceImpl
 * @pakeage:cn.yunyichina.provider.base.service.impl
 */
@Service
public class DeptServiceImpl {

	@Autowired
	private DeptDao deptDao;

	@Autowired
	private OrgSettingDao orgSettingDao;

	@Autowired
	private PlatformDeptRelationDao platformDeptRelation;
	private static final Logger logger = LoggerFactory.getLogger(DeptServiceImpl.class);
	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 
	 * @methodName:selectDept
	 * @description:查询数据医院科室
	 * @author:yangfan
	 * @date:2016年11月8日
	 * @param data
	 * @return:Response
	 */
	public Response selectdataDept(String data) {
		Response response = new Response();
		Dept dept = JsonUtils.parseObject(data, Dept.class);
		List<Dept> list = this.deptDao.select(dept);
		response.setResult(JsonUtils.toJsonString(list));
		response.setResultCodeAndMessage("0", "查询成功");
		logger.info("医院科室查询成功");
		return response;
	}


	/**
	 * 获取可用部门
	 * @param data
	 * @interfaceName: yyt.base.dept.get
	 * @return
	 */
	public Response getDept(String data) {
		Response response = new Response();
		Dept dept = JsonUtils.parseObject(data, Dept.class);
		List<Dept> list = this.deptDao.select(dept);
		if(list.size() > 0){
			response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE, Response.SUCCESS_MESSAGE ,JsonUtils.toJsonString(list));
		}else{
			response.setResultCodeAndMessage(Response.FAILURE_CODE, Response.FAILURE_MESSAGE);
		}
		return response;
	}

	/**
	 * 
	 * @methodName:selecthisDept
	 * @description:查询his医院科室,并做数据更新
	 * @author:yangfan
	 * @date:2016年11月8日
	 * @param data
	 * @param sessionId
	 * @return:Response
	 */
	@Transactional
	public Response selecthisDept(String data,String sessionId) {
		Response response = new Response();
		SessionInfo sessions = CacheService.getSessionInfo(sessionId);
		if (null == sessions) {
			response.setResultCodeAndMessage("1101", "用户信息为空，请先登录");
			return response;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
		// 医院code
		String org_code = maps.get("org_code");
		if (StringUtils.isBlank("org_code")) {
			response.setResultCodeAndMessage("1101", "医院编码为空");
			return response;
		}
 
		OrgSetting org = new OrgSetting();
		org.setOrgCode(org_code);
		// 根据医院code查询到sys_org_setting医院配置的org_id和org_name
		List<OrgSetting> orgList = this.orgSettingDao.select(org);
		if (null == orgList || orgList.size() == 0) {
			response.setResultCodeAndMessage("1101", "医院不存在");
			return response;
		}

		// 从his获取医院科室数据
		List<Dept> hislist = new ArrayList<Dept>();
		
		//Comorg_code
		RegisterDeptsVo registerDeptsVo = new RegisterDeptsVo();
		registerDeptsVo.setBranchCode(orgList.get(0).getHisCode());
		registerDeptsVo.setHospitalCode(orgList.get(0).getOrgCode());
		
		ResCommon<List<RegisterDeptsVoResponse>> deptResponse = HisifaceService.getHisifaceClient().getRegisterDepts(registerDeptsVo);
		List<RegisterDeptsVoResponse> deptlistresponse = deptResponse.getResult();
		for (RegisterDeptsVoResponse registerDeptsVoResponse : deptlistresponse) {
			Dept dept = new Dept();
			dept.setDeptName(registerDeptsVoResponse.getDeptName());
			dept.setDeptCode(registerDeptsVoResponse.getDeptCode());
			dept.setDeptTel(registerDeptsVoResponse.getDeptTelephone());
			dept.setDeptType(Short.valueOf("0"));
			dept.setDescription(registerDeptsVoResponse.getDeptDescription());
			dept.setAddress(registerDeptsVoResponse.getDeptLocation());
			dept.setCreatedBy(sessions.getUserName());
			dept.setCreatedTime(sdf.format(new Date()));
			dept.setEnableFlag(Short.valueOf("1"));
			dept.setParentId(registerDeptsVoResponse.getParentDeptCode());
			dept.setId(PKGenerator.generateId());
			dept.setOrgId(orgList.get(0).getOrgId());
			dept.setOrgName(orgList.get(0).getOrgName());
			hislist.add(dept);
		}
		
		if (null == hislist || hislist.size() == 0) {
			response.setResultCodeAndMessage("0", "获取医院科室成功，无科室数据");
			return response;
		}
		
		// 从平台获取对应医院的科室数据
		Dept dpselect = new Dept();
		dpselect.setOrgId(orgList.get(0).getOrgId());
		List<Dept> list = this.deptDao.select(dpselect);
		
		// 用医院科室和平台的本地数据进行匹配，有新科室数据则入库
		List<Dept> newList = new ArrayList<Dept>();
		Map<String, Dept> map = new HashMap<String, Dept>();
		if (null != list || list.size() != 0) {
			// 把医院科室数据放入map
			for (Dept dept : hislist) {
				map.put(dept.getDeptCode(), dept);
			}
			// 对平台对应医院科室进行匹配,如果没有，则为医院新科室
			for (Dept dept : list) {
				if (null == map.get(dept.getDeptCode())) {
					newList.add(dept);
				}
			}
		}

		
		// 如果有新的科室则进行入库医院科室，入库平台与医院科室关系对照。
		if (newList.size() > 0) {
			List<PlatformDeptRelation> platlist = new ArrayList<PlatformDeptRelation>();
			for (int i = 0; i < newList.size(); i++) {
				newList.get(i).setId(PKGenerator.generateId());
				newList.get(i).setCreatedTime(sdf.format(new Date()));
				newList.get(i).setCreatedBy(sessions.getUserId());
				
				PlatformDeptRelation pl = new PlatformDeptRelation();
				pl.setId(PKGenerator.generateId());
				pl.setHospitalId(orgList.get(0).getOrgId());
				pl.setHospitalName(orgList.get(0).getOrgName());
				pl.setHospitalDeptId(newList.get(i).getDeptCode());
				platlist.add(pl);
			}
			try {
				this.deptDao.batchInsert(newList);
				logger.info("入库医院科室数据成功");
				this.platformDeptRelation.batchInsert(platlist);
				logger.info("入库平台医院科室关系数据成功");
				response.setResultCodeAndMessage("0", "添加医院科室成功");
			} catch (Exception e) {
				response.setResultCodeAndMessage("1999", "入库医院科室异常");
				return response;
			}
			// 入库之后，组合vo数据返回给平台
		}else{
			response.setResultCodeAndMessage("0", "获取医院科室成功，无新科室数据");
		}
		return response;
	}


	/**
	 * 新增骨科合作医院
	 * @param data
	 * @return
	 */
	public Response addDept(String data){
		Response response = new Response();
		try {
			logger.info("新增仁医骨科部门开始");
			DeptVo request = JsonUtils.parseObject(data,DeptVo.class);
			Dept dept = new Dept();
			dept.setId(PKGenerator.generateId());
			dept.setEnableFlag(new Short("1"));
			dept.setDeptCode(PinyinUtils.getChineseFirstWord(request.getDeptName()));
			dept.setDeptName(request.getDeptName());
			dept.setOrgName(request.getOrgName());
			dept.setOrgId(request.getOrgId());
			dept.setCreatedTime(simpleDateFormat.format(new Date()));
			logger.info("新增仁医骨科部门结束");
			deptDao.insert(dept);
			response.setResultCodeAndMessage("0","成功");
			return response;
		}catch (Exception e){
			logger.error("新增科室异常",e);
			return Response.failure();
		}

	}

	/**
	 * 根据医院id 获取科室列表
	 * @param data
	 * @return
	 */
	public ResponseObject getDeptByOrgId(String data){
		ResponseObject responseObject = new ResponseObject();
		try {
			JSONObject request =  JSONObject.parseObject(data);
			String orgId = request.getString("org_id");
			List <cn.yunyichina.provider.base.entity.Dept> depts =  deptDao.selectDeptByOrgId(orgId);
			responseObject.setResultCodeAndMessageAndResult("0","成功",depts);
			return responseObject;
		}catch (Exception e){
			logger.error("查询科室异常",e);
			responseObject.setResultCodeAndMessage("-1","查询科室异常");
			return responseObject;

		}

	}



}
